/* eslint-disable */
import legacyPlugin from '@vitejs/plugin-legacy';
import {createSvgIconsPlugin} from 'vite-plugin-svg-icons' // 支持svg
import * as path from 'path';
import {createVuePlugin} from 'vite-plugin-vue2';
import vitePluginVueDeep from "./vite-plugin-vue-deep";
import vitePluginChangeMain from "./vite-plugin-change-main";
import {cjs2esmVitePlugin} from 'cjs2esmodule'
import vitePluginDynamicImport from "./vite-plugin-dynamic-import";
import vitePluginChangeImportdev from './vite-plugin-change-importdev'
import {vitePluginNodeModules__RequireChange} from "./vite-plugin-node_modules__require-change";
import {loadEnv, defineConfig, DepOptimizationOptions} from "vite";
import changeRequireContext from "./vite-plugin-require-change/changeRequireContext";
import changeRequire from "./vite-plugin-require-change/changeRequire";
import Utils from "./utils";
// @see https://cn.vitejs.dev/config/
// @ts-ignore
export default defineConfig(({command, mode}) => {
  let envPrefix = ['VUE_APP_', 'VITE_']
  const env = loadEnv(mode, process.cwd(), envPrefix)
  process.env = {
    ...env,
    ...process.env
  }
  const vueConfigJs = require('./../vue.config')

  function getWebpackVarToClient() {
    const result = {}
    const value = process.env
    if (!value) {
      return result
    }
    Object.keys(value)
      .filter(key => key.startsWith(envPrefix[0]))
      .forEach(key => {
        result['process.env.' + key] = `"${value[key]}"`
      })
    return result
  }

  let rollupOptions = {};
  const coreJs = Utils.readDirectory(process.cwd()+'/node_modules/core-js/modules',false,/\/es.*.js$/);
  /**
   * 启动预构建
   */
  let optimizeDeps: DepOptimizationOptions = {
    include: [
      ...Object.keys(coreJs),
      'echarts',
      'vue-splitpane',
      'print-js'
    ]
  };


  let alias = {
    '@': path.resolve(process.cwd(), './src'),
    '~@': path.resolve(process.cwd(), './src'), // 兼容webpack在url中的写法
    '~element-ui': path.resolve(process.cwd(), './node_modules/element-ui'), // 使用别名识别：~element-ui
    '~@riophae': path.resolve(process.cwd(), './node_modules/@riophae'), // 使用别名识别：~@riophae
    'vue$': 'vue/dist/vue.runtime.esm.js',
    'vue-codemirror-lite': 'vue-codemirror-lite/dist/vuecodemirror.min.js',
    'sql-formatter/dist/sql-formatter.min.js': 'sql-formatter',
    'vuedraggable': path.resolve(process.cwd(), './node_modules/vuedraggable/dist/vuedraggable.umd.min.js')
  }
  // todo 替换为原有变量
  let define = {
    'process.env.NODE_ENV': command === 'serve' ? '"development"' : '"production"',
    ...getWebpackVarToClient()
  }
  return {
    base: './', // index.html文件所在位置
    root: './', // js导入的资源路径，src
    resolve: {
      extensions: ['.vue', '.mjs', '.js', '.ts', '.jsx', '.tsx', '.json'],
      alias,
    },
    envPrefix,
    define: define,
    server: {
      ...vueConfigJs.devServer, // 导入vue.config.js的服务配置
      open: false,
      host: '0.0.0.0',
    },
    build: {
      target: 'es2015',
      minify: 'terser', // 是否进行压缩,boolean | 'terser' | 'esbuild',默认使用terser
      manifest: false, // 是否产出maifest.json
      sourcemap: false, // 是否产出soucemap.json
      outDir: 'build', // 产出目录
      rollupOptions,
    },
    esbuild: {},
    optimizeDeps,
    plugins: [
      createVuePlugin({
        jsx: true
      }),
      legacyPlugin({
        targets: ['Android > 39', 'Chrome >= 60', 'Safari >= 10.1', 'iOS >= 10.3', 'Firefox >= 54', 'Edge >= 15'],
      }),
      vitePluginVueDeep(),
      createSvgIconsPlugin({
        iconDirs: [path.join(process.cwd(), 'src/icons/svg')],
        symbolId: 'icon-[name]',
        inject: 'body-first'
      }),
      cjs2esmVitePlugin(), // 将 commonjs 转化为 es module
      vitePluginChangeMain(), // 在main.js|ts中插入 import 'virtual:svg-icons-register' 支持svg
      ...((includes = []) => { // 这三个一起用，用于处理第三方插件
        // vue-codemirror-lite 这个无法处理，使用别名
        return [
          vitePluginNodeModules__RequireChange(includes),
          changeRequireContext(includes),
          changeRequire(includes),
        ]
      })([]), // ['vue-codemirror-lite']
      vitePluginDynamicImport(),
      vitePluginChangeImportdev(),
    ],
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: (content, filePath) => {
            return `@import "~@/styles/theme-var.scss";
          ${content}`
          }
        },
      }
    },
  };
})

// http://127.0.0.1:9081/vite-replace-webpack-dev/index.html
